﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using static System.Console;

namespace 自定义事件委托
{
    // 委托
    public delegate void MessageHandler(string messageText);

    internal class Program
    {
        // 事件委托
        public event MessageHandler MessageArrived;

        private Timer pollTimer;
        private static Random random = new Random();

        public Program() 
        { 
            pollTimer = new Timer(1000);
            pollTimer.Elapsed += new ElapsedEventHandler(CheckForMessage);
        }

        public void Connect() => pollTimer.Start();
        public void Disconnect() => pollTimer.Stop();

        private void CheckForMessage(object source,ElapsedEventArgs e)
        {
            WriteLine("Checking for new message");
            if((random.Next(9) == 0 )&& (MessageArrived != null))
            {
                //MessageArrived("hello Donna!");
                MessageArrived.Invoke("hello Donna!");
            }
        }



        static void Main(string[] args)
        {
            Program p = new Program();
            Display d = new Display();

            // p.MessageArrived += new MessageHandler(d.DisplayMessage);
            p.MessageArrived += d.DisplayMessage;
            p.Connect();

            ReadKey();
        }
    }

    public class Display
    {
        public void DisplayMessage(string message) => WriteLine($" message arrived:{message}");
    }
}
